<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 保存表单配置接口 - 表单增删改、令牌生成管理
 * 尊重劳动成果是一种美德
 */

error_reporting(0);
ini_set('display_errors', 0);

header('Content-Type: application/json; charset=utf-8');

// 日志函数已禁用
// function writeSchemaLog($message, $level = 'INFO') {}

try {
    $action = $_POST['action'] ?? '';
    // writeSchemaLog("=== 表单管理请求 - Action: {$action} ===");
    
    if (!in_array($action, ['add', 'update', 'delete', 'generate_token', 'edit_token', 'delete_token'])) {
        // writeSchemaLog("错误: 无效的操作 - {$action}", 'ERROR');
        throw new Exception('无效的操作');
    }
    
    $configFile = __DIR__ . '/../config.php';
    
    if (!file_exists($configFile)) {
        throw new Exception('配置文件不存在');
    }
    
    $config = require $configFile;
    $schemas = $config['schemas'] ?? [];
    
    // 确保default表单存在
    if (!isset($schemas['default'])) {
        $schemas['default'] = [
            'schema_key' => 'default',
            'schema_name' => '默认表单',
            'schema_code' => $config['schema_code'] ?? '',
            'schema_desc' => '主表单',
            'token_id' => '',
            'token_secret' => ''
        ];
    }
    
    // 转换为索引数组
    $schemaList = [];
    foreach ($schemas as $key => $schema) {
        $schema['schema_key'] = $key;
        $schemaList[] = $schema;
    }
    
    if ($action === 'add') {
        // 新增表单
        $name = trim($_POST['schema_name'] ?? '');
        $code = trim($_POST['schema_code'] ?? '');
        $desc = trim($_POST['schema_desc'] ?? '');
        $imageFieldsJson = trim($_POST['image_fields'] ?? '[]');
        $attachmentFieldsJson = trim($_POST['attachment_fields'] ?? '[]');
        
        if (empty($name) || empty($code)) {
            throw new Exception('表单名称和编码不能为空');
        }
        
        // 检查编码是否重复
        foreach ($schemaList as $schema) {
            if ($schema['schema_code'] === $code) {
                throw new Exception('表单编码已存在');
            }
        }
        
        // 解析字段数组
        $imageFields = json_decode($imageFieldsJson, true) ?: [];
        $attachmentFields = json_decode($attachmentFieldsJson, true) ?: [];
        
        // 生成schema_key
        $schemaKey = 'schema_' . substr(md5(uniqid()), 0, 8);
        
        $schemaList[] = [
            'schema_key' => $schemaKey,
            'schema_name' => $name,
            'schema_code' => $code,
            'schema_desc' => $desc,
            'image_fields' => $imageFields,
            'attachment_fields' => $attachmentFields,
            'token_id' => '',
            'token_secret' => ''
        ];
        
        // writeSchemaLog("新增表单: {$name} ({$code}), Key: {$schemaKey}");
        
    } elseif ($action === 'update') {
        // 更新表单
        $index = intval($_POST['index'] ?? -1);
        
        if ($index < 0 || $index >= count($schemaList)) {
            throw new Exception('无效的表单索引');
        }
        
        $name = trim($_POST['schema_name'] ?? '');
        $code = trim($_POST['schema_code'] ?? '');
        $desc = trim($_POST['schema_desc'] ?? '');
        $imageFieldsJson = trim($_POST['image_fields'] ?? '[]');
        $attachmentFieldsJson = trim($_POST['attachment_fields'] ?? '[]');
        
        if (empty($name) || empty($code)) {
            throw new Exception('表单名称和编码不能为空');
        }
        
        // 检查编码是否与其他表单重复
        foreach ($schemaList as $idx => $schema) {
            if ($idx !== $index && $schema['schema_code'] === $code) {
                throw new Exception('表单编码已存在');
            }
        }
        
        // 解析字段数组
        $imageFields = json_decode($imageFieldsJson, true) ?: [];
        $attachmentFields = json_decode($attachmentFieldsJson, true) ?: [];
        
        $schemaList[$index]['schema_name'] = $name;
        $schemaList[$index]['schema_code'] = $code;
        $schemaList[$index]['schema_desc'] = $desc;
        $schemaList[$index]['image_fields'] = $imageFields;
        $schemaList[$index]['attachment_fields'] = $attachmentFields;
        
        // writeSchemaLog("更新表单: {$name} ({$code}), Index: {$index}");
        
    } elseif ($action === 'delete') {
        // 删除表单
        $index = intval($_POST['index'] ?? -1);
        
        if ($index < 0 || $index >= count($schemaList)) {
            throw new Exception('无效的表单索引');
        }
        
        // 不允许删除default表单
        if ($schemaList[$index]['schema_key'] === 'default') {
            throw new Exception('不能删除主表单');
        }
        
        array_splice($schemaList, $index, 1);
        
        // writeSchemaLog("删除表单: Index {$index}");
        
    } elseif ($action === 'generate_token') {
        // 生成令牌 - 符合api.php标准
        $index = intval($_POST['index'] ?? -1);
        
        if ($index < 0 || $index >= count($schemaList)) {
            throw new Exception('无效的表单索引');
        }
        
        // 生成 token_id：9位随机字符串（大小写字母+数字）
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        $tokenId = '';
        for ($i = 0; $i < 9; $i++) {
            $tokenId .= $chars[random_int(0, strlen($chars) - 1)];
        }
        
        // 生成 token_secret：24位随机字符串（大小写字母+数字）
        $tokenSecret = '';
        for ($i = 0; $i < 24; $i++) {
            $tokenSecret .= $chars[random_int(0, strlen($chars) - 1)];
        }
        
        $schemaList[$index]['token_id'] = $tokenId;
        $schemaList[$index]['token_secret'] = $tokenSecret;
        
        // writeSchemaLog("生成令牌: Index {$index}, TokenID: {$tokenId}");
        
        $responseData = [
            'token_id' => $tokenId,
            'token_secret' => $tokenSecret
        ];
        
    } elseif ($action === 'edit_token') {
        // 编辑令牌
        $index = intval($_POST['index'] ?? -1);
        
        if ($index < 0 || $index >= count($schemaList)) {
            throw new Exception('无效的表单索引');
        }
        
        $tokenId = trim($_POST['token_id'] ?? '');
        $tokenSecret = trim($_POST['token_secret'] ?? '');
        
        if (empty($tokenId) || empty($tokenSecret)) {
            throw new Exception('令牌ID和密钥不能为空');
        }
        
        // 验证 token_secret 长度（24位）
        if (strlen($tokenSecret) !== 24) {
            throw new Exception('令牌密钥必须为24位');
        }
        
        $schemaList[$index]['token_id'] = $tokenId;
        $schemaList[$index]['token_secret'] = $tokenSecret;
        
        // writeSchemaLog("编辑令牌: Index {$index}, TokenID: {$tokenId}");
        
    } elseif ($action === 'delete_token') {
        // 删除令牌
        $index = intval($_POST['index'] ?? -1);
        
        if ($index < 0 || $index >= count($schemaList)) {
            throw new Exception('无效的表单索引');
        }
        
        // 不允许删除default表单的令牌
        if ($schemaList[$index]['schema_key'] === 'default') {
            throw new Exception('不能删除主表单的令牌');
        }
        
        $schemaList[$index]['token_id'] = '';
        $schemaList[$index]['token_secret'] = '';
        
        // writeSchemaLog("删除令牌: Index {$index}");
    }
    
    // 转换回关联数组
    $schemas = [];
    foreach ($schemaList as $schema) {
        $key = $schema['schema_key'];
        unset($schema['schema_key']);
        $schemas[$key] = $schema;
    }
    
    // 更新配置
    $config['schemas'] = $schemas;
    
    // 写入配置文件
    $configContent = "<?php\n";
    $configContent .= "/**\n";
    $configContent .= " * 氚云API管理系统配置文件\n";
    $configContent .= " * Alyr.net 企业级配置管理\n";
    $configContent .= " */\n\n";
    $configContent .= "// 氚云API配置\n";
    $configContent .= "return " . var_export($config, true) . ";\n";
    
    if (!file_put_contents($configFile, $configContent)) {
        // writeSchemaLog("错误: 写入配置文件失败", 'ERROR');
        throw new Exception('写入配置文件失败');
    }
    
    // writeSchemaLog("操作成功 - {$action}");
    // writeSchemaLog('=== 表单管理请求结束 ===');
    
    $response = [
        'success' => true,
        'message' => '操作成功'
    ];
    
    if (isset($responseData)) {
        $response = array_merge($response, $responseData);
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    $errorMsg = $e->getMessage();
    // writeSchemaLog("异常: {$errorMsg}", 'ERROR');
    // writeSchemaLog('=== 表单管理请求异常结束 ===');
    
    echo json_encode([
        'success' => false,
        'message' => $errorMsg
    ]);
}
